package com.ruiao.car.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RedisConfig {

    @Value("${redis.pool.maxActive}")
    private int maxTotal;

    @Value("${redis.pool.maxIdle}")
    private int maxIdle;

    @Value("${redis.pool.minIdle}")
    private int minIdle;

    @Value("${redis.pool.maxWaitMillis}")
    private int maxWaitMillis;


    @Autowired
    private Environment env;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        return config;
    }

    @Bean
    public JedisPool jedisPool() {

        String host = env.getProperty("redis.host");
        int port = Integer.parseInt(env.getProperty("redis.port"));
        int timeout = Integer.parseInt(env.getProperty("redis.timeout"));
        String password = env.getProperty("redis.password");
        int database = Integer.parseInt(env.getProperty("redis.database"));
        JedisPool pool = new JedisPool(jedisPoolConfig(), host, port, timeout, password, database);

        return pool;
    }

    @Bean
    public Jedis jedis() {

        return jedisPool().getResource();

    }

}
